<template>
  <el-row :gutter="24">

    <el-col :span="24">
      <el-card style="margin-bottom: 10px">
        距离考试结束还有：<span style="color: #ff0000;">{{ hour }}:{{ min }}:{{ sec }}</span>
        <el-button style="float: right; margin-top: -10px" type="primary" icon="el-icon-plus" :loading="loading"
                   @click="handHandExam()">
          {{ handleText }}
        </el-button>

      </el-card>
    </el-col>

    <el-col :span="6" :xs="24" style="margin-bottom: 10px">

      <el-card>

        <p class="card-title">答题卡</p>
        <el-row :gutter="24" class="card-line" style="padding-left: 10px">
          <el-tag type="info">未作答</el-tag>
          <el-tag type="success">已作答</el-tag>
        </el-row>


        <div v-if="paperData.radioList!==undefined && paperData.radioList.length > 0">
          <p class="card-title">单选题</p>
          <el-row :gutter="24" class="card-line">
            <el-tag v-for="item in paperData.radioList" :type="cardItemClass(item.answered, item.id)"
                    @click="quIndex=item.sort-1" :key="'radioTag'+item.id" v-if="item.sort<10"> 0{{item.sort}}
            </el-tag>
            <el-tag v-for="item in paperData.radioList" :type="cardItemClass(item.answered, item.id)"
                    @click="quIndex=item.sort-1" :key="'radioTag'+item.id" v-if="item.sort>=10"> {{item.sort}}
            </el-tag>
          </el-row>
        </div>

        <div v-if="paperData.multiList!==undefined && paperData.multiList.length > 0">
          <p class="card-title">多选题</p>
          <el-row :gutter="24" class="card-line">
            <el-tag v-for="item in paperData.multiList" :key="'multiTag'+item.id"
                    :type="cardItemClass(item.answered, item.id)"
                    @click="quIndex=item.sort-1">{{ item.sort }}
            </el-tag>
          </el-row>
        </div>

        <div v-if="paperData.fillList!==undefined && paperData.fillList.length > 0">
          <p class="card-title">填空题</p>
          <el-row :gutter="24" class="card-line">
            <el-tag v-for="item in paperData.fillList" :type="cardItemClass(item.answered, item.id)"
                    :key="'fillTag'+item.id"
                    @click="quIndex=item.sort-1">{{ item.sort }}
            </el-tag>
          </el-row>
        </div>

      </el-card>

    </el-col>

    <el-col :span="18" :xs="24">

      <el-card class="qu-content" v-if="allItem[quIndex]">
        <p>{{ allItem[quIndex].sort}}.{{ allItem[quIndex].text }}</p>
        <div v-if="allItem[quIndex].questionType === '1'">
          <el-radio-group v-model="radioValue">
            <el-radio class="answersItem" v-for="item in allItem[quIndex].questionAnswerList" :label="item.id"
                      :key="'Answers'+item.id">{{item.text}}
            </el-radio>
          </el-radio-group>
        </div>
        <div v-if="allItem[quIndex].questionType === '2'">
          <el-checkbox-group v-model="multiValue">
            <el-checkbox class="answersItem" v-for="item in allItem[quIndex].questionAnswerList" :label="item.id"
                         :key="'Answers'+item.id">{{item.text }}
              <div v-if="item.image" style="clear: both"/>
            </el-checkbox>
          </el-checkbox-group>
        </div>

      </el-card>

      <div style="margin-top: 20px">
        <el-button v-if="quIndex!=0" type="primary" icon="el-icon-back" @click="handNext(-1)">
          上一题
        </el-button>
        <el-button v-if="quIndex!=allItem.length-1" type="warning" icon="el-icon-right" @click="handNext(1)">
          下一题
        </el-button>
      </div>

    </el-col>

  </el-row>
</template>

<script>
  import { getUserPaper, updateUserPaper } from '@/api/exam/userPaper'

  export default {
    name: 'exam-start',
    data() {
      return {
        // 全屏/不全屏
        loading: false,
        handleText: '交卷',
        updateCount: 0,
        //题目索引
        quIndex: -1,
        // 试卷ID
        paperId: '',
        // 当前答题卡全部题目
        allItem: [],

        // 试卷信息
        paperData: {
          leftSeconds: -1,
          radioList: [],
          multiList: [],
          fillList: []
        },
        // 单选选定值
        radioValue: '',
        // 多选选定值
        multiValue: [],
        // 已答ID
        answeredIds: [],
        hour: '00',
        min: '00',
        sec: '00'
      }

    },
    watch: {

      //监听题目变化
      quIndex: {
        handler(oldValue, newValue) {
          this.radioValue = ''
          this.multiValue = []
          let question = this.allItem[this.quIndex]
          // 填充该题目的答案
          question.questionAnswerList.forEach((item) => {
            if (question.questionType === '1' && item.checked === '1') {
              this.radioValue = item.id
            }
            if (question.questionType === '2' && item.checked === '1') {
              this.multiValue.push(item.id)
            }
          })
        }
      }
    },

    created() {
      const id = this.$route.params && this.$route.params.paperId
      this.paperId = id
      const loading = this.$loading({
        text: '拼命加载中',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getUserPaper(id).then(response => {
        if (response.data.status === '2') {
          const obj = { path: '/exam/userPaper' }
          this.$tab.closeOpenPage(obj)
          loading.close()
          return
        }
        this.allItem = JSON.parse(response.data.questionList)
        this.allItem.sort((a, b) => a.questionType - b.questionType)
        if (this.paperData.leftSeconds === -1) {
          this.paperData.leftSeconds = response.data.userTime * 60
          this.countdown()
        }

        this.allItem.forEach((o, index) => {
          o.sort = index + 1
          if (o.questionType === '1') {
            this.paperData.radioList.push(o)
          }
          if (o.questionType === '2') {
            this.paperData.multiList.push(o)
          }
          if (o.questionType === '3') {
            this.paperData.fillList.push(o)
          }
        })
        this.quIndex = 0
        loading.close()
      })

    },

    methods: {

      // 倒计时
      countdown() {
        const leftSeconds = this.paperData.leftSeconds

        // 强制交卷
        if (leftSeconds < 0) {
          this.doHandler()
          return
        }

        // 时
        const min = parseInt(leftSeconds / 60 % 60)
        const hour = parseInt(leftSeconds / 3600)
        const sec = parseInt(leftSeconds % 60)

        this.min = min > 9 ? min : '0' + min
        this.sec = sec > 9 ? sec : '0' + sec
        this.hour = hour > 9 ? hour : '0' + hour

        this.paperData.leftSeconds -= 1
        setTimeout(() => {
          this.countdown()
        }, 1000)
      },

      // 答题卡样式
      cardItemClass(answered, questionId) {
        if (questionId === this.allItem[this.quIndex].id) {
          return 'warning'
        }

        if (answered) {
          return 'success'
        }

        if (!answered) {
          return 'info'
        }
      },

      /**
       * 统计有多少题没答的
       * @returns {number}
       */
      countNotAnswered() {
        let notAnswered = 0
        this.allItem.forEach(function(item) {
          if (!item.answered) {
            notAnswered += 1
          }
        })
        return notAnswered
      },

      /**
       * 换题
       */
      handNext(i) {
        this.handSave()
        this.quIndex += i
      },

      doHandler() {
        this.handSave()
        this.handleText = '正在交卷，请等待...'
        updateUserPaper({
          id: this.paperId,
          questionList: JSON.stringify(this.allItem),
          userTime: Math.round(this.paperData.leftSeconds / 60)
        }).then(response => {
          this.loading = true
          const params = {
            id: this.paperId, status: '2',
            userTime: Math.round(this.paperData.leftSeconds / 60)
          }
          updateUserPaper(params).then(response => {
            this.$modal.msgSuccess('交卷成功')
            this.loading = false
            this.$tab.closeOpenPage({ path: '/study/userPaper', query: {} })
          })
        })

      },

      // 交卷操作
      handHandExam() {

        updateUserPaper({
          id: this.paperId,
          questionList: JSON.stringify(this.allItem),
          userTime: Math.round(this.paperData.leftSeconds / 60)
        }).then(response => {
          const that = this
          this.handSave(function() {
            const notAnswered = that.countNotAnswered()
            let msg = '确认要交卷吗？'
            if (notAnswered > 0) {
              msg = '您还有' + notAnswered + '题未作答，确认要交卷吗?'
            }
            that.$confirm(msg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              that.doHandler()
            }).catch(() => {
              that.$message({
                type: 'info',
                message: '交卷已取消，您可以继续作答！'
              })
            })
          })
        })
        // 交卷保存答案

      },

      // 保存答案
      handSave(callback) {
        const answers = this.multiValue
        if (this.radioValue !== '') {
          answers.push(this.radioValue)
        }
        if (answers && answers.length !== 0) {
          this.setQuest()
        }
        if (callback) {
          callback()
        }
      },
      //设置内存和后台数据
      setQuest() {
        let item = this.allItem[this.quIndex]
        this.allItem.forEach(o => {
          if (item.id === o.id) {
            o.answered = 1
            o.questionAnswerList.forEach((a) => {
              if (item.questionType === '1') {
                if (this.radioValue === a.id) {
                  a.checked = '1'
                } else {
                  a.checked = '0'
                }
              }

              if (item.questionType === '2') {
                if (this.multiValue.indexOf(a.id) !== -1) {
                  a.checked = '1'
                } else {
                  a.checked = '0'
                }
              }
            })
          }
        })
        this.updateCount++
        if (this.updateCount > 4) {
          updateUserPaper({
            id: this.paperId,
            status: '1',
            questionList: JSON.stringify(this.allItem),
            userTime: Math.round(this.paperData.leftSeconds / 60)
          }).then(response => {
          })
          this.updateCount = 0
        }

      }

    }
  }
</script>

<style scoped>
  .qu-content p {
    white-space: pre-wrap;
  }

  .qu-content div {
    line-height: 30px;
  }

  .el-checkbox-group label, .el-radio-group label {
    width: 100%;
  }

  .card-title {
    background: #eee;
    line-height: 35px;
    text-align: center;
    font-size: 14px;
  }

  .card-line {
    padding-left: 10px
  }

  .card-line span {
    cursor: pointer;
    margin: 2px;
  }

  .answersItem {
    margin-left: 0;
  }

  /deep/
  .el-radio, .el-checkbox {
    padding: 9px 20px 9px 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-bottom: 10px;
  }

  .is-checked {
    border: #409eff 1px solid;
  }

  .el-radio img, .el-checkbox img {
    max-width: 200px;
    max-height: 200px;
    border: #dcdfe6 1px dotted;
  }

  /deep/
  .el-checkbox__inner {
    display: none;
  }

  /deep/
  .el-radio__inner {
    display: none;
  }

  /deep/
  .el-checkbox__label {
    line-height: 30px;
  }

  /deep/
  .el-radio__label {
    line-height: 30px;
  }
</style>
